//
//  PolicyDetailViewController.m
//  Village
//
//  Created by longrise on 2017/9/6.
//  Copyright © 2017年 程虎. All rights reserved.
//
#define TextFont [UIFont systemFontOfSize:16]
#import "PolicyDetailViewController.h"
#import "PolicyHeadView.h"
#import "AccessoryView.h"
#import "PolicyModel.h"
#import "AccessoryTableViewCell.h"
#import "ProgressView.h"
#import "LCDownloadManager.h"

#import "DocumentViewController.h"//查看文件
#import "NSMutableAttributedString+Extention.h"
#import "NSString+FindFace.h"
@interface PolicyDetailViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    BOOL fj;
}

@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) PolicyHeadView *policyview;
@property (nonatomic ,strong) UIView *scroview;
@property (nonatomic ,strong) AccessoryView *accview;
@property (nonatomic ,strong) UILabel *mainlable;
@property (nonatomic ,strong) UILabel *fujianlable;
@property (nonatomic ,strong) NSArray *fijiary;
@property (nonatomic, strong) ProgressView *prossView;
@property (nonatomic ,strong) UIWebView *web;

@property (nonatomic, copy, readonly) NSString *title1;//标题
@property (nonatomic, copy, readonly) NSString *publishcom;//发布单位
@property (nonatomic, copy, readonly) NSString *updatetime;//修改时间
@property (nonatomic, copy, readonly) NSString *content;//详细内容
@property (nonatomic, copy, readonly) NSString *readnum;//阅读量
@property (nonatomic, copy, readonly) NSString *creator;//阅读量
@property (nonatomic, strong) PolicyModel *model;
@end

@implementation PolicyDetailViewController

- (void)setParams:(id)obj block:(LongriseRouterBlock)block
{
    PolicyModel *poli = ( PolicyModel *)obj;
    self.model = ( PolicyModel *)obj;
        _title1 = poli.title;
    if (poli.readnum == nil){
         _readnum = @"0";
    }else{
         _readnum = poli.readnum;
    }
    
        _creator = poli.creator;
        _publishcom = poli.publishcom;
        _updatetime = poli.publishtime;
        _content = poli.content;
    if (poli.fj  == nil){
        fj = NO;
    }else{
        fj = YES;
    }
//    NSDictionary *dict = (NSDictionary *)obj;
//    _title1 = dict[@"title"];
//    _readnum = dict[@"readnum"];
//    _publishcom = dict[@"publishcom"];
//    _updatetime = dict[@"updatetime"];
//    _content = dict[@"content"];
}



- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    [self addfuji];
    // Do any additional setup after loading the view.
    self.title = @"政策法规";

//    _scroview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, KDeviceHeight)];
//    _scroview.scrollEnabled = YES;
//    _scroview.showsVerticalScrollIndicator = NO;
//    _scroview.showsHorizontalScrollIndicator = NO;
//    [_scroview flashScrollIndicators];
//    // 是否同时运动,lock
//    _scroview.directionalLockEnabled = YES;;
//    [self.view addSubview:_scroview];

    _scroview = [[UIView alloc] init];

    _policyview = [[PolicyHeadView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, 0)];
    _policyview.titlelable.text = _title1;
    _policyview.readlable.text = _readnum;
    _policyview.releselable.text = _creator;
    NSString *str =_updatetime;
    str = [str substringToIndex:10];//截取掉下标7之后的字符串
    _policyview.timelable.text = str;
    CGFloat height;
    if (kDeviceWidth <375){
          height = [self getHeightByWidth1:_policyview.titlelable.frame.size.width title:_policyview.titlelable.text font:_policyview.titlelable.font] +20;
    }else if (kDeviceWidth == 375){
          height = [self getHeightByWidth1:_policyview.titlelable.frame.size.width title:_policyview.titlelable.text font:_policyview.titlelable.font];
    }else{
         height = [self getHeightByWidth1:_policyview.titlelable.frame.size.width title:_policyview.titlelable.text font:_policyview.titlelable.font];
    }
//    --------------------------------------------------------------------
    _policyview.titlelable.frame = CGRectMake(16*kScreenScaleX, 24*kScreenScaleY, 343*kScreenScaleX, height*kScreenScaleY);
    CGFloat  width ;
    if (kDeviceWidth >375){
        width   = [self getWidthWithTitle:_creator font:[UIFont systemFontOfSize:12]] +15;
    }else{
        width   = [self getWidthWithTitle:_creator font:[UIFont systemFontOfSize:12]];
    }
    _policyview.releselable.frame = CGRectMake(30, (43 + height)* kScreenScaleY, width, 10);
    _policyview.timeimage.frame = CGRectMake((37 +width), (43 + height)* kScreenScaleY, 10, 10);
    CGFloat  width1 ;
    if (kDeviceWidth >375){
        width1   = [self getWidthWithTitle:str font:[UIFont systemFontOfSize:12]] +20;
    }else{
        width1   = [self getWidthWithTitle:str font:[UIFont systemFontOfSize:12]];
    }
    _policyview.timelable.frame = CGRectMake((50 +width), (43 + height)* kScreenScaleY, width1, 10);
    _policyview.readimage.frame = CGRectMake((53 +width +width1), (43 + height)* kScreenScaleY, 10, 10);
    _policyview.readlable.frame = CGRectMake((66 +width +width1), (43 + height)* kScreenScaleY, 50, 10);
//    --------------------------------------------------------------------
    //富文本设置
    
    _content = [self htmlEntityDecode:_content];
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[_content dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
    [NSNumber numberWithInt:NSUTF8StringEncoding];
    _policyview.frame = CGRectMake(0, 0, kDeviceWidth,(height+80)*kScreenScaleY);
    [_scroview addSubview:_policyview];
    _mainlable = [[UILabel alloc] initWithFrame:CGRectMake(16*kScreenScaleX, (height +80)*kScreenScaleY, 340*kScreenScaleX, 0)];
    _mainlable.attributedText = attrStr;
    _mainlable.font = [UIFont systemFontOfSize:16*kScreenScaleX];
     _mainlable.textColor = [Util colorWithHexString:@"666666"];
    _mainlable.numberOfLines = 0;
    [_mainlable sizeToFit];
    
    CGFloat height1;
    height1 = [self getHeightByWidth:_mainlable.frame.size.width title:_mainlable.attributedText font:_mainlable.font] ;
//    if (KDeviceHeight > 736){
//             height1 = [self getHeightByWidth:_mainlable.frame.size.width title:_mainlable.attributedText font:_mainlable.font] - 400;
//    }
    _mainlable.frame = CGRectMake(16*kScreenScaleX, height +80*kScreenScaleY, 340*kScreenScaleX, height1);
    [_scroview addSubview:_mainlable];

    if (fj == YES){
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(14*kScreenScaleX, height1+height+100*kScreenScaleY, 348*kScreenScaleX, 2*kScreenScaleY)];
        view.backgroundColor =  [Util colorWithHexString:@"f8f8f8"];
        [_scroview addSubview:view];
        _fujianlable = [[UILabel alloc] initWithFrame:CGRectMake(16*kScreenScaleX, height1+height+120*kScreenScaleY, 80*kScreenScaleX, 13*kScreenScaleY)];
         _fijiary = [NSArray array];
         _fijiary = [Tools toJSONData:self.model.fj];
         NSLog(@"--------fijiary：%@",_fijiary);
         NSString *str = [NSString stringWithFormat:@"附件"];
        _fujianlable.text = str;
        _fujianlable.textColor = [Util colorWithHexString:@"333333"];
        _fujianlable.font = [UIFont systemFontOfSize:14*kScreenScaleY];
        [_scroview addSubview:_fujianlable];
//        _accview = [[AccessoryView alloc] initWithFrame:CGRectMake(0, height1+height+150*kScreenScaleY, kDeviceWidth, 80*kScreenScaleY)];
//        _accview.model = self.model;
    }else{
    }
    _scroview.frame = CGRectMake(0, 0, kDeviceWidth,height1+height+140*kScreenScaleY );
    _tableView.tableHeaderView = _scroview;
}

#pragma mark - 附件
- (void)addfuji{
    _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.frame = CGRectMake(0, 0, kDeviceWidth, KDeviceHeight - 80);
    //   _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];//去除多余空白行
    [_tableView registerClass:[AccessoryTableViewCell class] forCellReuseIdentifier:@"AccessoryTableViewCell"];
    [self.view addSubview:_tableView];
}

#pragma mark - UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
     if (fj == YES){
           return 1;
     }else{
           return 0;
     }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (fj == YES){
        return _fijiary.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    cell = [tableView dequeueReusableCellWithIdentifier:@"AccessoryTableViewCell"];
    AccessoryTableViewCell *newcell = (AccessoryTableViewCell *)cell;
    NSDictionary *dict = self.fijiary[indexPath.row];
    newcell.fjStr = dict[@"httpurl"];
    newcell.Acclable.text = _fijiary[indexPath.row][@"title"];
    [newcell setSelectionStyle:UITableViewCellSelectionStyleNone];//cell点击之后没有视觉效果
    WeakSelf(weakSelf);
    newcell.downBlock = ^(NSInteger index) {
        if ([Globle getInstance].account.userid.length) {
            NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
            NSString *filePath = [path stringByAppendingPathComponent:@"policy.plist"];
            // 解档
            NSMutableArray *usersary = [[NSMutableArray alloc]initWithContentsOfFile:filePath];
            BOOL isbool = [usersary containsObject: dict[@"httpurl"]];
            if (isbool == 1){
                DocumentViewController *document = [[DocumentViewController alloc] init];
                document.url = dict[@"httpurl"];
                document.name = dict[@"title"];
                [self.navigationController pushViewController:document animated:YES];
//                [MBProgressHUD showError:@"暂不支持阅览" toView:weakSelf.navigationController.view];
            }else{
                 [weakSelf downloadFjWithIndex:indexPath.row];
            }
        }
        else {
            [MBProgressHUD showError:@"下载之前请先登录您的账号！" toView:weakSelf.navigationController.view];
        }
    };
    return cell;
}
- (void)downloadFjWithIndex:(NSInteger )index
{
    self.prossView = [[ProgressView alloc] init];
    [self.prossView show];
    NSDictionary *dict = self.fijiary[index];
    NSMutableArray *fileAry = [NSMutableArray array];
    NSMutableArray *nameAry = [NSMutableArray array];
    [fileAry addObject:dict[@"httpurl"]];
    [nameAry addObject:[NSString stringWithFormat:@"%@",dict[@"httpurl"]]];
    [[LCDownloadManager getInstanceWithuserflag:[Globle getInstance].account.userid withStoragePath:@"down_fj"] downloadFileWith:fileAry withNameArr:nameAry progressbloack:^(CGFloat progress, long long totalMBRead, long long totalMBExpectedToRead) {
        self.prossView.prossCount = progress;
    } successBlock:^(NSString *sucDownPath, NSString *SucDownName) {
        [self.prossView hide];
        NSDictionary *FJDict = [NSMutableDictionary dictionary];
        FJDict = [Util getDataForKey:[Globle getInstance].account.userid.length > 0 ? [Globle getInstance].account.userid : @""];
        NSArray *arys = FJDict[@"id"];
        NSMutableArray *arrays = [NSMutableArray arrayWithArray:arys];
        NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];
        if ([[FJDict allKeys] count]) {
            for (int i = 0; i < arys.count; i++) {
                if (![arys[i] isEqualToString:dict[@"httpurl"]]) {
                    [arrays addObject:dict[@"httpurl"]];
                    [self addary:dict[@"httpurl"]];
                }
            }
        }
        else {
            [arrays addObject:dict[@"httpurl"]];
            [dataDict setObject:arrays forKey:@"id"];
            [self addary:dict[@"httpurl"]];
        }
        [[Globle getInstance] saveAttachment:dataDict];
        [self.tableView reloadData];
    } failureBlock:^(NSError *error, NSString *errorDownPath, NSString *errorDowName) {
        [MBProgressHUD showError:@"下载失败，请检查您的网络重新下载！" toView:self.navigationController.view];
    }];

}
#pragma mark - 储存本地
/**
 本地储存
 @param idd 下载的文件id
 */
- (void)addary:(NSString *)idd{
    //                    ----------
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [path stringByAppendingPathComponent:@"policy.plist"];
    // 解档
    NSMutableArray *usersary = [[NSMutableArray alloc]initWithContentsOfFile:filePath];
    if (usersary.count == 0){
        usersary = [NSMutableArray array];
    }
    [usersary addObject:idd];
    [Tools Dictionariesplistname:usersary];
    //                    ----------
}
#pragma mark - labelTwo  SizeToFitWidth
//将 &lt 等类似的字符转化为HTML中的“<”等
- (NSString *)htmlEntityDecode:(NSString *)string
{
    string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    string = [string stringByReplacingOccurrencesOfString:@"&apos;" withString:@"'"];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"]; // Do this last so that, e.g. @"&amp;lt;" goes to @"&lt;" not @"<"
    //让图片自适应
    string = [NSString stringWithFormat:@"<head><style>img{max-width:340px !important;}</style></head>%@",string];
    return string;
}
- (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1000, 0)];
    label.text = title;
    label.font = font;
    [label sizeToFit];
    return label.frame.size.width;
}
- (CGFloat)getHeightByWidth:(CGFloat)width title:(NSAttributedString *)title font:(UIFont *)font
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
    label.attributedText = title;
    label.font = font;
    label.numberOfLines = 0;
    [label sizeToFit];
    CGFloat height = label.frame.size.height;
    return height;
}
- (CGFloat)getHeightByWidth1:(CGFloat)width title:(NSString *)title font:(UIFont *)font
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
    label.text = title;
    label.font = font;
    label.numberOfLines = 0;
    [label sizeToFit];
    CGFloat height = label.frame.size.height;
    return height;
}
@end
